//
//  BshopMiaoshuViewController.m
//  DistributorAB
//
//  Created by 主事丫环 on 2019/5/21.
//  Copyright © 2019 主事丫环. All rights reserved.
//

#import "BshopMiaoshuViewController.h"
#import "PIc9CollectionViewCell.h"
#import "TZImagePickerController.h"
#import "SYBigImage.h"

@interface BshopMiaoshuViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UITextViewDelegate,TZImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollview;


@property (weak, nonatomic) IBOutlet UILabel *numberLB;
@property (weak, nonatomic) IBOutlet UITextView *mytv;
@property(nonatomic,strong)NSMutableArray *imageArr;

@property(nonatomic,strong)UIImage *myimage;
@property(nonatomic,strong)UILabel *myimageLable;

@property(nonatomic,strong)NSMutableArray *assets;

@property(nonatomic,strong)UICollectionView *mycollectView;

@property(nonatomic,strong)UIView *bottomView;


@property(nonatomic,strong)NSString *delIds;


@end

@implementation BshopMiaoshuViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"产品描述";
    [self.leftbutton setImage:imgname(@"left_icon") forState:(UIControlStateNormal)];
    self.mytv.delegate= self;
    _delIds = @"";
    self.imageArr = [NSMutableArray arrayWithCapacity:1];
    self.assets = [NSMutableArray arrayWithCapacity:1];

    _scrollview.backgroundColor = [UIColor whiteColor];
    _scrollview.delegate = self;
    adjustInset(_scrollview);
    UIImageView *myimage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, (KWIDTH-6-32)/3, (KWIDTH-6-32)/3+12)];
    myimage.image = imgname(@"add9image");
//    self.myimageLable = [[UILabel alloc]init];
//    [myimage addSubview:self.myimageLable];
//    self.myimageLable.font = FontSize(12);
//    self.myimageLable.textColor = [UIColor colorWithHexString:@"#CECECE"];
//    [self.myimageLable mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.offset(0);
//        make.width.offset(100);
//        make.height.offset(17);
//        make.top.offset(62);
//    }];
    self.myimage = myimage.image;
    [self.imageArr addObject: self.myimage];
    
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((KWIDTH-6-32)/3 , (KWIDTH-6-32)/3);
//    _mycollectView.collectionViewLayout =layout;
    _mycollectView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, KWIDTH, (KWIDTH-6-32)/3+12+16) collectionViewLayout:layout];
    [self.scrollview addSubview:_mycollectView];
    //        layout.headerReferenceSize = CGSizeMake(KWIDTH, 204);
    layout.sectionInset = UIEdgeInsetsMake(0, 16, 0, 3);
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    adjustInset(_mycollectView);
    _mycollectView.dataSource = self;
    _mycollectView.delegate = self;
//    _mycollectView.backgroundColor =RGBA(237, 237, 237, 1);
    _mycollectView.backgroundColor = [UIColor whiteColor];
    [_mycollectView registerNib:[UINib nibWithNibName:@"PIc9CollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"PIc9CollectionViewCell"];
    
    [_mycollectView reloadData];
    
    
    CGFloat yyyy = KHEIGHT -_mycollectView.bottom-162;
    CGFloat hei = 162;
    if (yyyy > 0) {
        hei = hei+yyyy;
    }
    
    self.bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, _mycollectView.bottom, KWIDTH, hei)];
    self.bottomView.backgroundColor = [UIColor colorWithHexString:@"#F2F2F2"];
    [self.scrollview addSubview: self.bottomView ];
    
    UIButton *baocun = [UIButton buttonWithType:(UIButtonTypeCustom)];
    baocun.frame = CGRectMake(28, 96, KWIDTH-56, 48);
    baocun.layer.masksToBounds = YES;
    baocun.layer.cornerRadius = 4;
    [baocun setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [baocun setBackgroundColor:[UIColor colorWithHexString:@"#70BE68"]];
    [baocun setTitle:@"保存" forState:(UIControlStateNormal)];
    [baocun addTarget:self action:@selector(baocunaction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.bottomView addSubview:baocun];
    self.scrollview.contentSize = CGSizeMake(KWIDTH, self.bottomView.bottom);
    
    
    if (_model) {
        
        
        NSInteger ind =_model.product_info.length;
        if (ind<301) {
            ind = 300-ind;
            self.numberLB.text = [NSString stringWithFormat:@"%ld/300",ind];
            
        }
        
        
        
        
        
        self.mytv.text = _model.product_info;
        [_imageArr removeAllObjects];
    
    for (NSDictionary *mudic in _model.imgs) {
        NSString *urlstr =[NSString stringWithFormat:@"%@",[mudic objectForKey:@"product_img_url"]];
        
        [_imageArr addObject:urlstr];
        
        
        
    }
        
        [self.imageArr addObject: self.myimage];
        
        [_mycollectView reloadData];
        if (_imageArr.count<4) {
            _mycollectView.height= (KWIDTH-6-32)/3+12+16;
            
        }else if(_imageArr.count<7){
            _mycollectView.height = ((KWIDTH-6-32)/3+12)*2+16;
            
            
        }else{
            _mycollectView.height = ((KWIDTH-6-32)/3+12)*3+16;
            
        }
        
        CGFloat yyyy = KHEIGHT -_mycollectView.bottom-162;
        CGFloat hei = 162;
        if (yyyy > 0) {
            hei = hei+yyyy;
        }
        self.bottomView.y =_mycollectView.bottom;
        self.bottomView.height =yyyy;
        self.scrollview.contentSize = CGSizeMake(KWIDTH, self.bottomView.bottom);
    }
    
}
-(void)baocunaction:(UIButton *)but{
    //保存
    if (strIsEmpty(_mytv.text)) {
        ShowToastWithText(@"请输入产品描述");
        return;
    }
    if (_imageArr.count == 1) {
        ShowToastWithText(@"请选择产品图片");
        return;

    }
    [_imageArr removeLastObject];
    
    for (int i = 0; i <_imageArr.count; i
         ++) {
        if ([_imageArr[i] isKindOfClass:[NSString class]]) {
            [_imageArr removeObjectAtIndex:i];
        }
    }
    
    if (self.myblock) {
        self.myblock(_imageArr, _mytv.text,_delIds);
    }
    [self.navigationController popViewControllerAnimated:YES];
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    NSInteger ind =textView.text.length;
     NSString *newString = [textView.text stringByReplacingCharactersInRange:range withString:text];
    ind = newString.length;
    
    if (ind<301) {
        ind = 300-ind;
        if (ind < 0) {
            ind = 0;
        }
        self.numberLB.text = [NSString stringWithFormat:@"%ld/300",ind];

        return YES;
    }else{

        return NO;
    }
}
//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
//{
//
//    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
//    NSInteger length = [self textLength:newString];//转换过的长度
//    NSLog(@"%@------长度: %ld",newString,length);
//
//        NSInteger ind =300-length;
//    self.numberLB.text = [NSString stringWithFormat:@"%ld/300",ind];
//
//    if (length > 300)
//    {
//        return NO;
//    }
//
//    return YES;
//}
-(NSUInteger)textLength: (NSString *) text{
    
    NSUInteger asciiLength = 0;
    
    for (NSUInteger i = 0; i < text.length; i++) {
        
        
        unichar uc = [text characterAtIndex: i];
        
        //设置汉字和字母的比例  如何限制4个字符或12个字母 就是1:3  如果限制是6个汉字或12个字符 就是 1:2  一次类推
        asciiLength += isascii(uc) ? 1 : 2;
    }
    
    NSUInteger unicodeLength = asciiLength;
    
    return unicodeLength;
    
}
- ( CGSize )collectionView:( UICollectionView *)collectionView layout:( UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:( NSIndexPath *)indexPath {
    return CGSizeMake((KWIDTH-6-32)/3 , (KWIDTH-6-32)/3);
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (_imageArr.count == 10) {
        return 9;
    }else{
        
    return _imageArr.count;
    }
    
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
        if (_imageArr.count == 10) {
            ShowToastWithText(@"最多选择9张");
            return;
        }
        
        if(indexPath.row == (_imageArr.count-1)){
            NSInteger inn = 9 - _imageArr.count;
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:inn columnNumber:4 delegate:self pushPhotoPickerVc:YES];
        imagePickerVc.sortAscendingByModificationDate = NO;
        imagePickerVc.selectedAssets = _assets;
        [self presentViewController:imagePickerVc animated:YES completion:nil];
        }else{
            //查看大图
            
        }
    
}
#pragma mark - TZImagePickerControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    if ([picker isKindOfClass:[UIImagePickerController class]]) {
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker {
}

// 当选择器自己dismiss的时候，会执行下面的代理方法
// isSelectOriginalPhoto 选择了原图
// asset通过：[[TZImageManager manager] getOriginalPhotoWithAsset:completion:]获得原图
// photos数组里的UIImage对象，默认是828像素宽，你可以通过设置photoWidth属性的值来改变它
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    [_imageArr removeAllObjects];
    [_assets removeAllObjects];

   
    if (_model) {
        self.mytv.text = _model.product_info;
        [_imageArr removeAllObjects];
        
        for (NSDictionary *mudic in _model.imgs) {
            NSString *urlstr =[NSString stringWithFormat:@"%@",[mudic objectForKey:@"product_img_url"]];
            
            [_imageArr addObject:urlstr];
            
            
            
        }
    }
    
    
    
    
    
    
    
    [_imageArr addObjectsFromArray:photos];
    
    
    
    
 
      [_imageArr addObject:_myimage];
    
    [_assets addObjectsFromArray:assets];
    [self.mycollectView reloadData];
    
    if (_imageArr.count<4) {
     _mycollectView.height= (KWIDTH-6-32)/3+12+16;
     
    }else if(_imageArr.count<7){
        _mycollectView.height = ((KWIDTH-6-32)/3+12)*2+16;
     

    }else{
      _mycollectView.height = ((KWIDTH-6-32)/3+12)*3+16;
   
    }
    
    CGFloat yyyy = KHEIGHT -_mycollectView.bottom-162;
    CGFloat hei = 162;
    if (yyyy > 0) {
        hei = hei+yyyy;
    }
    self.bottomView.y =_mycollectView.bottom;
    self.bottomView.height =yyyy;
    self.scrollview.contentSize = CGSizeMake(KWIDTH, self.bottomView.bottom+kTabbarHeight);

}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    PIc9CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PIc9CollectionViewCell" forIndexPath:indexPath];
    cell.deleAction.hidden = NO;

    if ([_imageArr[indexPath.row] isKindOfClass:[UIImage class]]) {
        cell.myconImage.image = [_imageArr safeObjectAtIndex:indexPath.row];

    }else{
        
        NSString *strdf =[_imageArr safeObjectAtIndex:indexPath.row];
        [cell.myconImage sd_setImageWithURL:[NSURL URLWithString:strdf]];
    }
    if (_imageArr.count != 10) {
        if(indexPath.row == (_imageArr.count-1)){
            cell.deleAction.hidden = YES;
            self.myimageLable = [[UILabel alloc]init];
            [cell.contentView addSubview:self.myimageLable];
            self.myimageLable.font = FontSize(12);
            self.myimageLable.textAlignment = NSTextAlignmentCenter;
            self.myimageLable.textColor = [UIColor colorWithHexString:@"#CECECE"];
            //            self.myimageLable.textColor = [UIColor redColor];
            [self.myimageLable mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.offset(-5);
                make.width.offset(100);
                make.height.offset(17);
                make.top.offset(80);
            }];
            NSInteger inddd = _imageArr.count-1;
            self.myimageLable.text = [NSString stringWithFormat:@"%ld/9",inddd];
        }
    }
    
   
    
    
    cell.myblock = ^(NSString * _Nonnull str) {
        NSString * sdfsd = [NSString stringWithFormat:@"%ld",indexPath.row];
        [self delete:sdfsd];
    };
    return cell;
}

-(void)delete:(NSString *)ind{
    NSInteger indd = [ind integerValue];
    if (self.model) {
        NSMutableArray *arr =[self.model.imgs mutableCopy];
        if (arr.count > indd) {
        NSDictionary *dafa = _model.imgs[indd];
        _delIds = [NSString stringWithFormat:@"%@,%@",_delIds,[dafa objectForKey:@"id"]];
        [_imageArr removeObjectAtIndex:indd];
        [arr removeObjectAtIndex:indd];
        self.model.imgs = arr;
        }else{
            //删除本地
            [_imageArr removeObjectAtIndex:indd];
            [_assets removeObjectAtIndex:indd-self.model.imgs.count];

        }
    }else{
    //删除本地
        [_imageArr removeObjectAtIndex:indd];
        [_assets removeObjectAtIndex:indd];
        
        
    }
    
    
    [_mycollectView reloadData];
    
    if (_imageArr.count<4) {
        _mycollectView.height= (KWIDTH-6-32)/3+12+16;
        
    }else if(_imageArr.count<7){
        _mycollectView.height = ((KWIDTH-6-32)/3+12)*2+16;
        
        
    }else{
        _mycollectView.height = ((KWIDTH-6-32)/3+12)*3+16;
        
    }
    
    CGFloat yyyy = KHEIGHT -_mycollectView.bottom-162;
    CGFloat hei = 162;
    if (yyyy > 0) {
        hei = hei+yyyy;
    }
    self.bottomView.y =_mycollectView.bottom;
    self.bottomView.height =yyyy;
    self.scrollview.contentSize = CGSizeMake(KWIDTH, self.bottomView.bottom+kTabbarHeight);
}


@end
